function strPathCheckAll(s){
    if(s == "yes"){
        $("input[name='strPathCheck']").each(function(i){
            $(this).prop("checked",true)
        });
    }else{
        $("input[name='strPathCheck']").each(function(i){
            $(this).prop("checked",false)
        });      
    }
}
//图片预览
function ShowImg(obj){
    let path = $(obj).attr("data-path")
   layer.open({
       type:1,
       title:"图片预览-" + path,
       content:"<div><img src='/img?t=" + path +"'/></div>",
       maxWidth:(PageWidth - 100),
       maxHeight:(PageHeight - 300)
    })
}
//获取时间的毫秒数
function getTimeNum(t){
    let reg = /ms/
    let res = t.split("ms") 
    if(!reg.test(t)){
        res[0] = parseFloat(res[0]) * 1000
    }
    res[0] = parseFloat(res[0])
    return res
}

function numToTime(n){
    return  n > 1000 ? (n / 1000).toFixed(2) + "s" :n + "ms"
}
//压力测试性能记录
function yaLiPerformance(num,model,requestUrl){
    num = parseFloat(num)
    let url = window.btoa(requestUrl)
    if(perFormance[model][url] == undefined){
        perFormance[model][url]  = {
            now:num,
            avg:num,
            max:num,
            min:num,
            numList:[num],
            dateList:[getTime()]
        }
    }else{
        perFormance[model][url].numList.push(num)
        perFormance[model][url].dateList.push(getTime())
        perFormance[model][url].now= num
        let numSum = 0
        let avg  = 0
        let max  = perFormance[model][url].max
        let min  = perFormance[model][url].min
        let numCount = perFormance[model][url].numList.length
        for(let i = 0; i < numCount; i++ ){
            numSum += perFormance[model][url].numList[i]
        }
        avg = (numSum/numCount).toFixed(2)
        perFormance[model][url].avg = avg

        perFormance[model][url].max = num > max ? num:max
        perFormance[model][url].min = num < min ? num:min

    }
    //画图
    createMap(perFormance[model][url].dateList,perFormance[model][url].numList)
    $(".performance").css("display","inline-block")
    let innerHTML = "网页/api压力测试(" + perFormance[model][url].numList.length + ")次记录报表【可拖动】"
    innerHTML    += "<hr/>&nbsp;&nbsp;地址：" +  requestUrl
    innerHTML    += "<br/>&nbsp;&nbsp;最新：" +  num
    innerHTML    += "<br/>&nbsp;&nbsp;最大：" +  perFormance[model][url].max 
    innerHTML    += "<br/>&nbsp;&nbsp;最小：" +  perFormance[model][url].min 
    innerHTML    += "<br/>&nbsp;&nbsp;平均：" +  perFormance[model][url].avg
    innerHTML    += `<br/>&nbsp;&nbsp;<button onclick="clearPerformanceLog('${model}','${url}')" style="font-size:14px;font-weight:normal;padding:5px;cursor:pointer">清空记录</button><span style='color:#ccc;font-size:12px;font-weight:normal;'> 记录如果过多，请及时清理，不然可能会影响浏览器性能！</span>`
    innerHTML    += `<div class='showNewNumber'>并发：${num}<hr/>性能：${checkYaCePerFormance(num)}</div>`
    $(".performance-haoshi").html(innerHTML)
   //更新缓存
   window.localStorage.setItem("perFormance",JSON.stringify(perFormance))
}
//api性能
function Performance(time,requestUrl){
    let model = $("#debugModel option:selected").val()
    let url = window.btoa(requestUrl)
    let timeRes = getTimeNum(time)

    if(perFormance[model][url] == undefined){
        perFormance[model][url]  = {
            now:time,
            avg:time,
            max:time,
            min:time,
            timeList:[timeRes[0]],
            dateList:[getTime()]
        }
    }else{
        perFormance[model][url].timeList.push(timeRes[0])
        perFormance[model][url].dateList.push(getTime())
        perFormance[model][url].now= time
        let timeSum = 0
        let avg  = 0
        let max  = getTimeNum(perFormance[model][url].max)
        let min  = getTimeNum(perFormance[model][url].min)
        let timeCount = perFormance[model][url].timeList.length
        for(let i = 0; i < timeCount; i++ ){
            timeSum += perFormance[model][url].timeList[i]
        }
        avg = (timeSum/timeCount).toFixed(2)
        perFormance[model][url].avg = numToTime(avg)

        perFormance[model][url].max = timeRes[0] > max[0] ? time:numToTime(max[0])
        perFormance[model][url].min = timeRes[0] < min[0] ? time:numToTime(min[0])

    }
    //画图
    createMap(perFormance[model][url].dateList,perFormance[model][url].timeList)
   //更新缓存
   window.localStorage.setItem("perFormance",JSON.stringify(perFormance))

    $(".performance").css("display","inline-block")
    let innerHTML = "Api模式get/post请求性能调试(" + perFormance[model][url].timeList.length + ")次记录报表【可拖动】"
    innerHTML    += "<hr/>&nbsp;&nbsp;地址：" +  requestUrl
    innerHTML    += "<br/>&nbsp;&nbsp;最新：" +  time
    innerHTML    += "<br/>&nbsp;&nbsp;最慢：" +  perFormance[model][url].max 
    innerHTML    += "<br/>&nbsp;&nbsp;最快：" +  perFormance[model][url].min 
    innerHTML    += "<br/>&nbsp;&nbsp;平均：" +  perFormance[model][url].avg
    innerHTML    += `<br/>&nbsp;&nbsp;<button onclick="clearPerformanceLog('${model}','${url}')" style="font-size:14px;font-weight:normal;padding:5px;cursor:pointer">清空记录</button><span style='color:#ccc;font-size:12px;font-weight:normal;'> 记录如果过多，请及时清理，不然可能会影响浏览器性能！</span>`
    innerHTML    += `<div class='showNewNumber'>耗时：${time}<hr/>性能：${checkPerFormance(timeRes[0])}</div>`
    $(".performance-haoshi").html(innerHTML)


}
//验证性能
function checkPagePerFormance(time){
    if(time <= 30){
        return '光速'
    }else if(time  > 30  && time < 50){
        return '极速'
    }else if(time  > 50  && time <= 80){
        return '神速'
    }else if(time  > 80  && time <= 100){
        return '快'
    }else if(time  > 100  && time <= 200){
        return '很快'
    }else if(time  > 200  && time <= 500){
        return '挺快'
    }else if(time  > 500  && time <= 1000){
        return '还行'
    }else if(time  > 1000  && time <= 2000){
        return '一般般'
    }else if(time  > 2000  && time <= 3000){
        return '有点慢'
    }else if(time  > 3000  && time <= 4000){
        return '不给力'
    }else if(time  > 4000  && time <= 5000){
        return '龟速'
    }else if(time  > 5000){
        return '赶紧优化'
    }
}
//验证性能
function checkPerFormance(time){
    if(time <= 10){
        return '光速'
    }else if(time  > 10  && time < 20){
        return '极速'
    }else if(time  > 20  && time <= 30){
        return '神速'
    }else if(time  > 30  && time <= 50){
        return '快'
    }else if(time  > 50  && time <= 100){
        return '很快'
    }else if(time  > 100  && time <= 300){
        return '挺快'
    }else if(time  > 300  && time <= 500){
        return '还行'
    }else if(time  > 500  && time <= 1000){
        return '一般般'
    }else if(time  > 1000  && time <= 2000){
        return '有点慢'
    }else if(time  > 2000  && time <= 3000){
        return '不给力'
    }else if(time  > 3000  && time <= 5000){
        return '龟速'
    }else if(time  > 5000){
        return '赶紧优化'
    }
}

//验证性能
function checkYaCePerFormance(num){
    if(num <= 10){
        return '别玩了'
    }else if(num  > 10  && num < 20){
        return '非常弱'
    }else if(num  > 20  && num <= 30){
        return '差劲'
    }else if(num  > 30  && num <= 50){
        return '请优化'
    }else if(num  > 50  && num <= 100){
        return '一般'
    }else if(num  > 100  && num <= 300){
        return '挺快'
    }else if(num  > 300  && num <= 500){
        return '快'
    }else if(num  > 500  && time <= 1000){
        return '强'
    }else if(num  > 1000  && num <= 2000){
        return '很强'
    }else if(num  > 2000  && num <= 5000){
        return '非常强'
    }else if(num  > 5000  && num <= 10000){
        return '极强'
    }else if(num  > 10000){
        return '秒杀一切'
    }
}
//clearPerformanceLog
function clearPerformanceLog(model,url){
    delete perFormance[model][url]
    window.localStorage.setItem("perFormance",JSON.stringify({perFormance}))
    layer.msg("清空成功！")
    $('.performance').hide("slow")
}
//createMap 画性能走势图
function createMap(catData,valueData){
        //$("#performance-map").html("")
        // 基于准备好的dom，初始化echarts实例
        let myChart = echarts.init(document.getElementById('performance-map'));
        // 指定图表的配置项和数据
        let option = {
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: catData,
                axisLabel: {
                    show: true,
                    textStyle: {
                        color: '#ffffff'
                    }
                }
            },
            yAxis: {
                type: 'value',
                axisLabel: {
                    show: true,
                    textStyle: {
                        color: '#fff'
                    }
                }
            },
            series: [{
                data: valueData,
                type: 'line',
                areaStyle: {},
                color:'pink'
            }]
        };
        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
}
function getTime(){
    let myDate = new Date();
    let t = "";
   // t +=  myDate.getFullYear() + "-";
   // t +=  (parseInt(myDate.getMonth()) + 1) + "-";
    //t +=  myDate.getDate() + " ";
    t +=  myDate.getHours() + ":";
    t +=  myDate.getMinutes() + ":";
    t +=  myDate.getSeconds();
    return t;
}
//有道翻译
function translation(){
    let  html = '<iframe src="http://fanyi.youdao.com/" frameborder="0"  id="translation" style="width:'+ (PageWidth - 100) +'px;height:'+ (PageHeight - 100) +'px;"></iframe>'
    layer.open({
        type:1,
        title:"有道词典-英汉翻译:",
        content:html,
        maxWidth:(PageWidth - 200),
        maxHeight:(PageHeight - 300)
     })  
}
//json格式化
function jsonFormat(){
    let  html = '<iframe src="http://json.cn/" frameborder="0"  id="translation" style="width:'+ (PageWidth - 100) +'px;height:'+ (PageHeight - 100) +'px;"></iframe>'
    layer.open({
        type:1,
        title:"json数据格式化:",
        content:html,
        maxWidth:(PageWidth - 200),
        maxHeight:(PageHeight - 300)
     })  
}
//弹窗
function layerShow(title,html){
    layer.open({
        type:1,
        title:title,
        content:html,
        maxWidth:(PageWidth - 100),
        maxHeight:(PageHeight - 300)
     })  
}
//获取当前sql数据
function GetSql(){
    let html = "<table  class='currentSql' style='width:1820px;'>"
    if($(".LogTable table tr .sql").length <= 1){
        layer.msg("暂时没有sql日志哦，赶紧调试吧!");
    }else{
        // $(".LogTable table tr .sql").each(function(i){
        //     if(i != 0){
        //         html += "<h3 style='padding:10px 15px 10px 15px;'>" + i + ")&nbsp;&nbsp;" +  $(this).text() + "</h3>"
        //     }
        // });
        html += $(".LogTable table").eq(1).html() + "</table>"
        layer.open({
            type:1,
            title:"当前SQL语句:",
            content:html,
            maxWidth:(PageWidth - 100),
            maxHeight:(PageHeight - 300)
        })  
    }
}
//
function setParamsChecked(obj){
    //先取消当前行所有的activ
    $(obj).parent("p").find("span").removeClass("params-span-active")
    $(obj).addClass("params-span-active")
    $(obj).parent("p").find("span input").prop("checked",false)
    $(obj).find("input").prop("checked",true)
}
function setChestParamsChecked(obj){
    //先取消当前行所有的activ
    $(obj).parent("p").find("span").removeClass("params-span-active")
    $(obj).addClass("params-span-active")
    $(obj).parent("p").find("span input").prop("checked",false)
    $(obj).find("input").prop("checked",true)
    changeChest(0)
}

function iniFileOpenLists(path){
    let str = "<button onclick='openDir()'>打开目录</button>"
    //让列表渲染
    for(let i = 0; i < fileOpenLists.length; i++){
        let childPath = fileOpenLists[i]
        let selected =""
        let arr = childPath.split("/")
        let NowFunc = "GetFileInfo"
        if (childPath == path) {
            selected = "selected"
        }
        str += "<button class='"+ selected + "' title='" + childPath + "' data-path='" + childPath + "' onclick='" + NowFunc + "(this)' data-isdir='file'>" + arr[(arr.length - 1)] +  "<span class='close'></span></button>"
    }
    $(".fileLists").html(str)
}

//发送替换
function strReplace(){
    let url = $("#url").val()
    let replaceStr = $("#strReplace").val()

    if(url.length < 1){
        layer.msg("搜索内容不能为空！")
    }else if($("input[name='strPathCheck']:checked").length < 1){
        layer.msg("抱歉您没有选择要替换的文件！")
    }else{
        let str = ""
        $("input[name='strPathCheck']:checked").each(function(i){
            if(i > 0){
                str += "|" + $(this).attr("data-path")
            }else{
                str += $(this).attr("data-path")
            }
        })
        let Data = {};
        Data.type = "STRREPLACE";
        Data.search = url;
        Data.replace = replaceStr;
        Data.files = str;
        ws.send(json(Data))
    }
    
}

//清空sql日志
function ClearSql(){
    let Data = {};
    Data.type = "CLEARSQL";
    ws.send(json(Data))  
    layer.msg("日志已被清空！")
}

//全文搜索和目录或文件搜索
function strSeach(type){
    let url = $("#url").val()
    let path = $(".nowPath").html()
    if(url.length < 2){
        layer.msg("大神为了减少电脑压力，请输入两个字符串以上的内容哦！")
    }else if(path.length < 1){
        layer.msg("请选择一个目录或文件！")
    }else{
        $(".apiBody pre").html("<p class='jindu'>大神，莫慌！后台正在玩命的搜索中......</p><p class='jindu-progress'>进度：<progress value='0' max='100.00'></progress> <span class='progress-span'>0</span>%</p><div class='jieguo'></div>")
        let Data = {};
        Data.type = type == 0 ?"STRSEARCH":"DIRSEARCH";
        Data.path = path;
        Data.data = url;
        ws.send(json(Data))  
    }
}
function openDir(){
    $("#lockPageDisplay").prop("checked",true)
    $(".setHetBox").show("slow")
}
function closeCodeBox(obj){
    $("#code").val("")
    $(".fileDir").html("")
    closeDiv(obj)
}
function closeSetHetBox(obj){
    $("#lockPageDisplay").prop("checked",false)
    closeDiv(obj)
}
//关闭
function closeDiv(obj){
    $(obj).parent().hide("slow")
}
//时间戳转日期
function timeToDate(){
    let url = $("#url").val()
    let reg = /^\d{10,}$/
    if(!reg.test(url)){
        layer.msg("大神，时间戳格式错误哦,时间戳是10位以上数字！")
    }else{
        $(".apiBody pre").html("<p class='jindu'>稍等，大神......</p><div class='jieguo'></div>")
        let Data = {};
        Data.type = "TIMETODATE";
        Data.data = url;
        ws.send(json(Data))  
    }
}
//拖曳
function Drag(){
    for(let i = 0; i < dragLists.length; i++){
        $(dragLists[i].element).Tdrag();
    }
}

//获取城市
function ipToCity(){
    let url = $("#url").val()
    if(!ipReg.test(url)){
        layer.msg("ip格式错误哦！")
        return
    }
    let Data = {};
    Data.type = "IPTOCITY";
    Data.data = $("#url").val();
    ws.send(json(Data))
}
function openEdit(){
    if(fileOpenLists.length < 1){
        layer.msg("您得先打开一个文件先哦！")
        return 
    }
    $(".codeBox").show("slow")
    let path = $(".fileLists .selected").attr("data-path")
    let Data = {};
    Data.type = "GetFileInfo";
    Data.data = path;
    ws.send(json(Data))
}
//关闭打开文件
function removeEdit(obj){
    let n = fileOpenLists.length
    let i = fileOpenLists.indexOf($(obj).parent().attr("data-path"))
    if(n > 1){
        let j = i + 1
        if(i == (n - 1)){
            j = i -1   
        }
        let Data = {};
        Data.type = "GetFileInfo";
        Data.data = fileOpenLists[j];
        ws.send(json(Data))
    }else{
        $("#code").val("")
        $(".fileDir").html("")
        $(".codeBox").hide("slow")
    }
    fileOpenLists.splice(i,1)
    $(obj).parent().remove()
}
//获取文件信息
function GetFileInfo(obj){
    let model = $("#debugModel option:selected").val()
    let path = $(obj).attr("data-path")
    //网页 api模式
    if($.inArray(model,fileSystemModels) != -1){
        $(".codeBox").show("slow");
    }
   // $(obj).attr("data-path")
   let Data = {};
   Data.type = "GetFileInfo";
   Data.data = $(obj).attr("data-path");
   ws.send(json(Data))
}
//获取文件夹信息
function GetPathInfo(obj){
   // $(obj).attr("data-path")
   //暂存器记录
   CurrentDir = $(obj).attr("data-path");
   let Data = {};
   Data.type = "GetPathInfo";
   Data.data = $(obj).attr("data-path");
   ws.send(json(Data))
}
//新建目录
function addDir(){
    let Path = $(".setHetBox .nowPath").html()
    let name = $("#addDirName").val()
    let type = $("input[name='addDir']:checked").val()
    if(Path.length < 1){
        layer.msg("当前目录不可新建！")
    }else if(name.length < 1){
        layer.msg("目录或文件名称不能为空！")
    }else{
        let Data = {};
        Data.type = "ADDDIR";
        Data.addtype = type;
        Data.path = Path;
        Data.name = name;
        ws.send(json(Data))
    }
}

//绑定删除事件
function bindDel(){
    $(".dirLists li .close").each(function(i){
        $(this).bind("click",function(event){
            event.stopPropagation(); //阻止冒泡
            delDir(this)
        })
    });
}
//删除目录
function delDir(obj){
    let path = $(obj).parent().attr("data-path")
    let Data = {};
    Data.type = "DELDIR";
    Data.path = path;
    Data.nowPath = $(".nowPath").html();
    ws.send(json(Data))
}
//输入框寄存器
function updateModelsUrlValues(){
    let model = $("#debugModel option:selected").val()
    let url = $("#url").val()
    modelsUrlValues[model] = url
}
//关闭修改高度
function closeiframeHeightSet(){
    $(".setHetBox").hide("slow")
}

//修改iframe显示宽度
function iframeWidthSet(){
    let w = parseFloat($("#iframeWidthSet").val())
    w = w || 1920
    let iframeWidth =  w + "px"
    let mysqlBoxWidth = ( parseFloat(window.screen.width) - w ) + "px"
    $("#iframe,.apiBody").animate({
        width:iframeWidth 
    },800)
}
//修改代码编辑器的宽度
function codeBoxWidthSet(){
    let w = parseFloat($("#codeBoxWidthRange").val())
    let codeBoxWidth =  w + "px"
    $(".codeBox").animate({
        width:codeBoxWidth 
    },800)  
    if(codeMain != null){
        openEdit()
    }
}
//修改滚动条长度
function ChangeCodeBoxWidth(){
    let w = parseFloat($(".codeBox").width()) - 100
    $("#codeBoxWidthRange").animate(
        {
            width: w + "px"    
        }
    ) 
}
//修改字体大小
function SetFontSize(obj){
    $(".codeBox .codeMain").css({
        fontSize:$(obj).val() + "px"
    })
}
function SetLang(){
    let lan = $("#SetLang").find("option:selected").text();
    Lang(codeMain,lan + "." + lan)
}
//修改编程语言
function Lang(obj,path){
    let  res  = path.split(".")
    let  name = res[res.length - 1]
    let  CReg = 0 //验证是否识别到
    for(let i = 0; i < Langs.length; i++){
        if(name == Langs[i][0]){
            obj.getSession().setMode("ace/mode/"+ Langs[i][1]);
            //修改编程语言修改项
            $("#SetLang").find("option").eq(i).prop("selected",true)
            CReg++
            break
        }
    }
    if(CReg == 0){
        obj.getSession().setMode("ace/mode/html"); //默认没匹配初始化为html
        $("#SetLang").find("option").eq(0).prop("selected",true)
    }
    $(".codeBox").show("slow")
}
//修改iframe高度
function setIframeHeight(){
    let h = $("#iframeHeightSet").val()
    let top = "-" + h + "px"
    let height = (parseFloat(h) + parseFloat(window.screen.height)) + "px" 
    let url = $("#url").val()
    if(!reg.test(url)){
        ShowMsg("大神，请先填写网址然点击开始才能更好的查阅修改高度哦")
        $("#iframeHeightSet").val(0)
    }else{
        $("#iframe").animate({
            top:top,
            height:height //高度要同步修改
        },800)
    }
}
//正则替换
function regReplaceStr(){
    let regxp = buildRegxp()
    let res = $("#regStr").val()
    str  = res.replace(regxp,$("#ReplaceStr").val())
    $(".replacesStr").val(str)
}
//正则表达式
function regXp(){
    if($("#url").val().length < 1) {
        ShowMsg("大神，规则为空哦！")
    }else if($("#regStr").val().length < 1){
        ShowMsg("大神，内容为空哦！")
    }else{
        let regxp = buildRegxp()
        let res = $("#regStr").val().match(regxp)
        if (null == res || res.length < 1){
            ShowMsg("大神，没有匹配到哦！")
        }else{
            $(".replaceSpan").html(`需要替换的内容：<input type="text" id="ReplaceStr" placeholder="大神，请随意填写！" onkeyup="regReplaceStr()"><button onclick="regReplaceStr()" id="regReplaceStr">走你</button>`)
            let str = ''
            let regstr = ''
            for(let i = 0; i < res.length; i++){
                regstr += res[i] + "\n"
            }
            str += "<div class='regedBox'><h1>匹配到的内容</h1><textarea style='font-size:18px;width:" + (parseInt(PageWidth) / 2 - 50) + "px;height:"  + (parseInt(PageHeight) / 3 - 50) + "px'>" + regstr + "</textarea></div>";
            str += "<br/><h1>替换后的内容</h1><textarea class='replacesStr' style='font-size:18px;width:" + (parseInt(PageWidth) / 2 - 50) + "px;height:"  + (parseInt(PageHeight) / 3 - 50) + "px'></textarea>";
           
            ShowMsg(str)
        }
    }
}

//保存代码
function Code(){   
    let code = codeMain.getValue()
    let model = $("#debugModel option:selected").val()
    let path = $(".fileDir").html()
    let Data = {};
    Data.type = "CODE";
    Data.path = path;
    Data.data = code;
    ws.send(json(Data)) 
    if($.inArray(model,fileSystemModels) != -1){
        DeBug()
    }
}
//页面抓取效果切换
function pageGet(){
    if(id("pageGet").checked){
        $(".pageGetBox").show("slow");
    }else{
        $(".pageGetBox").hide("slow"); 
    }
}
//抓取页面
function GetPageContent(){
    let pageGetInput = $("#pageGetInput").val()
    if(!reg.test(pageGetInput)){
        layer.msg("大神，请检查页面地址是否正确！")
    }else{
        let Data = {};
        Data.type = "REGXP";
        Data.data = pageGetInput;
        ws.send(json(Data)) 
    }
}
//buildregxp
function buildRegxp(){
    let options = ""
    options += id("regGlobal").checked ? "g" : ""
    options += id("regCase").checked ? "i" : ""
    return new RegExp($("#url").val(), options);
}